<!--医生： 视频问诊界面 -->
<template>
  <div class="MyContainer">
      <el-row style="min-height: 650px;">
          <el-col v-if="connectUser" :lg="17" class="flex justify-center items-center">
            <div class="videoBox" >
              <div class="local-video">
                <video id = "local-video" autoplay></video>
              </div>
              <div class="remote-video" >
                <video id= "remote-video"  autoplay></video>
              </div>
              <el-tooltip class="box-item" effect="dark" content="挂断" placement="top">
                <div class="test" :class="{'hover':video.peerStarted}" @click="hangUp">
                  <el-icon :size="30" color="#fff"><Close /></el-icon>
                </div>
              </el-tooltip>
              <el-tooltip class="box-item" effect="dark" content="连接" placement="top">
                <div v-if="!video.peerStarted" class="test" :class="{'hover':!video.peerStarted}" style="background-color:forestgreen;" @click="connect">
                  <el-icon :size="30" color="#fff"><PhoneFilled /></el-icon>
                </div>
              </el-tooltip>
            </div>
            <!-- <el-button @click="connect()">connect</el-button> -->
          </el-col>
          <el-col :lg="list_width">
              <div class="mt-4 flex">
                  <span class="ml-3 w-35 text-gray-600"> 用户名 </span>
                  <el-input style="/*width: 300px;*/" v-model="input" placeholder="请输入用户名" class="input-with-select">
                      <template #append>
                          <el-button :icon="Search" />
                      </template>
                  </el-input>
              </div> 
          <!-- 表格 -->
          <el-table :data="tableData" style="width: 100%" max-height="600px">
            <el-table-column prop="username" label="用户姓名" />
              <!-- <el-table-column prop="phone" label="联系电话"/>  -->
              <!-- <el-table-column prop="sex" label="性别" /> -->
              <!-- 操作  -->
            <el-table-column fixed="right" label="操作" >
              <template #default="scope">
                <el-button text @click="Connect(scope.row.username)" link type="primary">
                  <el-tag v-if="!video.peerStarted || scope.row.username !== index">建立连接</el-tag>
							    <el-tag v-if="!video.peerStarted && scope.row.username === index && connectUser" type="warning">连接中</el-tag>
							    <el-tag v-if="video.peerStarted && scope.row.username === index" type="success">连接成功</el-tag>
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          </el-col>
      </el-row>
  </div>
          
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search,Close,PhoneFilled } from '@element-plus/icons-vue'
import { useGlobleStore } from '../../store/globle';
import { getAcceptedInfo,getBookedDoc } from '../../api/manager';

const input = ref('')
const hover = ref(false)
const list_width = ref(24)
const connectUser = ref(false)
const index = ref('')
const globle = useGlobleStore()
//定义表格数据类型
interface TableItem {
  username:string,
}
//定义视频数据类型
interface Video {
  socket:any,
  socketRead:boolean,
  peerStarted:boolean,
  localVideo:any,
  localStream:any,
  mediaConstraints : any,
  peerConnection:any,
  remoteVideo:any
}
const tableData = ref<TableItem[]>([]);

function inList(list,user){
	var res = false
	//console.log("list.length:",list.length)
	if(list.length != undefined){
		list.forEach(element => {
			//console.log("list-ele:",element.cusName,"user:",user)
			if(element.docName === user){
				res = true;
			}
		});
	}
	return res
}

// 获取表格数据
const getData = () => {
var accept : TableItem[]
getBookedDoc().then(res=>{
  if(res.code === 200){//请求成功
    var list = res.data
    //console.log("res:",res)
    var url = "ws://47.113.217.179:8080/websocket/" + globle.getUsrname()
    var socket = new WebSocket(url)
    tableData.value = []
    socket.onmessage = function(res){
      var user = JSON.parse(res.data)
      console.log("签约：",list)
      console.log("在线",user.users)
      tableData.value = user.users.filter(use => use.username != globle.getUsrname() && inList(list,use.username));
    }
  }
}).catch(err=>{

})

};
getData();

//点击同意之后的弹窗提示
const Connect = (username) => {
  connectUser.value = true
  list_width.value = 7
  ElMessageBox.confirm(
    '是否与该用户建立视频问诊连接',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    //console.log(username)
    ElMessage({
      type: 'success',
      message: username,
    })
    startVideo()
    connectUsr(username)
  })
  .catch((err) => {
    console.log("err:",err)
      ElMessage({
          type: 'info',
          message: '取消操作',
      })
      connectUser.value = false
      list_width.value = 24
  })
}

const video = reactive<Video>({
socket:null,
socketRead:false,
  peerStarted:false,
  localVideo:document.getElementById('local-video'),
  localStream:null,
  mediaConstraints : {
  'mandatory': {
    'OfferToReceiveAudio': false,
    'OfferToReceiveVideo': true
  }
},
  peerConnection:null,
  remoteVideo:document.getElementById('remote-video')
})

const connectUsr = (username) =>{
  index.value = username
  var url = "ws://47.113.217.179:8080/videoServer/" + username
  video.socketRead = false;
  video.socket = new WebSocket(url)
  video.socket.onopen = function(){
    console.log("连接成功")
    video.socketRead = true
  }

  video.socket.onclose = function(e){
    console.log("连接关闭",e.code)
    video.socketRead = false
  }

  video.socket.onmessage = function(res) {
  var evt = JSON.parse(res.data)
  console.log("evt",evt)
  tableData.value = res.data
    if (evt.type === 'offer') {
      console.log("接收到offer,设置offer,发送answer....")
      onOffer(evt);
    } else if (evt.type === 'answer' && video.peerStarted) {
      console.log('接收到answer,设置answer SDP');
      onAnswer(evt);
    } else if (evt.type === 'candidate' && video.peerStarted) {
        console.log('接收到ICE候选者..');
      onCandidate(evt);
    } else if (evt.type === 'bye' && video.peerStarted) {
      console.log("WebRTC通信断开");
      stop();
    }
  }
}

function onOffer(evt) {
  console.log("接收到offer...")
  console.log(evt);
  setOffer(evt);
  sendAnswer(evt);
  video.peerStarted = true
  list_width.value = 7;
}

function onAnswer(evt) {
  console.log("接收到Answer...")
  console.log(evt);
  setAnswer(evt);
}

function onCandidate(evt) {
var candidate = new RTCIceCandidate({
  sdpMLineIndex: evt.sdpMLineIndex,
  sdpMid: evt.sdpMid,
  candidate: evt.candidate
});
      
  console.log("接收到Candidate...")	
  console.log(candidate);
  video.peerConnection.addIceCandidate(candidate);
}

function sendSDP(sdp) {
  var text = JSON.stringify(sdp);
  console.log('发送sdp.....')
  console.log(text); // "type":"offer"....
  // textForSendSDP.value = text;
  // 通过socket发送sdp
  video.socket.send(text)
}

    
function sendCandidate(candidate) {
  var text = JSON.stringify(candidate);
  console.log(text); // "type":"candidate","sdpMLineIndex":0,"sdpMid":"0","candidate":"....
  video.socket.send(text) // socket发送
}

//---------------------- 视频处理 -----------------------
function startVideo() {
  video.localVideo = document.getElementById('local-video')
  video.remoteVideo = document.getElementById('remote-video')
  navigator.mediaDevices.getUserMedia({
    video:true,
    audio:true
  }).then(stream =>{
    video.localStream = stream
    console.log("localStream:",video.localStream)
    video.localVideo.srcObject = stream
    video.localVideo.play()
    video.localVideo.volume = 0;
  }).catch(err=>{
    console.log("err=>(195:)",err)
  })
}

function refreshPage() {
  location.reload();
}

//---------------------- 处理连接 -----------------------
function prepareNewConnection() {
  var pc_config = {
    "iceServers": [{
      url: "stun:47.113.217.179:3478"
    }, {
      url: "turn:47.113.217.179:3478",
      credential: "kurento",
      username: "kurento"
    }]
  };
  var peer : any;
  try {
    peer = new webkitRTCPeerConnection(pc_config);
    console.log("peer:",peer)
  } catch (e) {
    console.log("建立连接失败，错误：" + e.message);
  }

  // 发送所有ICE候选者给对方
  peer.onicecandidate = function(evt) {
    if (evt.candidate) {
      console.log(evt.candidate);
      sendCandidate({
        type: "candidate",
        sdpMLineIndex: evt.candidate.sdpMLineIndex,
        sdpMid: evt.candidate.sdpMid,
        candidate: evt.candidate.candidate
      });
    }
  };
  console.log('添加本地视频流...');
  peer.addStream(video.localStream);
  peer.addEventListener("addstream", onRemoteStreamAdded, false);
  peer.addEventListener("removestream", onRemoteStreamRemoved, false);

  // 当接收到远程视频流时，使用本地video元素进行显示
  function onRemoteStreamAdded(event) {
    console.log("添加远程视频流");
    // remoteVideo.src = window.URL.createObjectURL(event.stream);
    video.remoteVideo.srcObject = event.stream;
    console.log("remote:",event.stream)
  }

  // 当远程结束通信时，取消本地video元素中的显示
  function onRemoteStreamRemoved(event) {
      console.log("移除远程视频流");
      video.remoteVideo.src = "";
    }
    return peer;
}

function sendOffer() {
  video.peerConnection = prepareNewConnection();
  video.peerConnection.createOffer(
    (sessionDescription) => { //成功时调用
      video.peerConnection.setLocalDescription(sessionDescription);
      console.log("发送: SDP");
      console.log(sessionDescription);
      sendSDP(sessionDescription);
    }, 
    (err) => { //失败时调用
      console.log("创建Offer失败");
    }, 
    video.mediaConstraints);
}

function setOffer(evt) {
  if (video.peerConnection) {
    console.error('peerConnection已存在!');
    return;
  }
  video.peerConnection = prepareNewConnection();
  video.peerConnection.setRemoteDescription(new RTCSessionDescription(evt));
}

function sendAnswer(evt) {
  console.log('发送Answer,创建远程会话描述...');
  if (!video.peerConnection) {
    console.error('peerConnection不存在!');
    return;
  }

  video.peerConnection.createAnswer(
    (sessionDescription) => { //成功时
      video.peerConnection.setLocalDescription(sessionDescription);
      console.log("发送: SDP");
      console.log(sessionDescription);
      sendSDP(sessionDescription);
    }, 
    (err) => { //失败时
      console.log("创建Answer失败",err);
    }, 
    video.mediaConstraints);
}

function setAnswer(evt) {
  if (!video.peerConnection) {
    console.error('peerConnection不存在!');
    return;
  }
  video.peerConnection.setRemoteDescription(new RTCSessionDescription(evt));
}

//-------- 处理用户UI事件 -----
// 开始建立连接
function connect() {
  if (!video.localStream) {
    alert("请首先捕获本地视频数据.");
  } else if (video.peerStarted || !video.socketRead) {
    alert("请刷新页面后重试.");
  } else {
    sendOffer();
    video.peerStarted = true;
    list_width.value = 7;
  }
}

// 停止连接
function hangUp() {
  console.log("挂断.");
  stop();
  refreshPage()
}

function stop() {
  video.peerConnection.close();
  video.peerConnection = null;
  video.peerStarted = false;
  connectUser.value = false
  list_width.value = 24
  //video.localStream.getTracks()[0].stop()
  //video.localStream.getTracks()[1].stop()
  //video.localStream = null
}
</script>

<style scoped>
.remote-video {
  /* width: 25%; */
  width: 800px;
  height: 600px;
  overflow: hidden;
}

.videoBox:hover > .hover{
  transform: translateY(-100px);
  transition: 0.5s ease-in;
}

.test{
  display: flex;
  justify-content: center;
  align-items: center;
  /* border: 1px solid #000; */
  background-color: #e63f3f;
  width: 45px;
  height: 45px;
  position: absolute;
  bottom: -50px;
  right: calc(50%);
  border-radius: 50px;
}

.local-video {
  width: 240px;
  height: 180px;
  position: absolute;
  right: 0;
  bottom: 0;
  border-radius: 10px 0 0 0;
  overflow: hidden;
}

.videoBox{
  position: relative;
  width: 800px;
  height: 600px;
  /* border:1px solid #ca1e1e; */
  background-color: beige;
  overflow: hidden;
  border-radius: 10px;
}

video{
  width: 100%;
  height: 100%;
}
</style>
